package nfwx.analytics;

import java.util.HashMap;
import java.util.Map;

/**
 * 采集参数，对象类型
 */

public class GrabObject extends GrabValue {

    private Map<String, GrabValue> _values;

    public GrabObject(boolean mustHasValue)
    {
        super(mustHasValue);
        _values = new HashMap<>();
    }

    public GrabValue defineProperty(String name, GrabValue val)
    {
        if (val._parent != null) throw new Error("Value to add alreay has a parent");
        if (_values.containsKey(name)) {
            throw new Error("Property name already exists");
        }
        _values.put(name, val);
        val._parent = this;
        if (val.getChanged()) {
            incChanged();
        }
        if (val.getHasValue()) {
            incHasValue();
        }
        return val;
    }

    public GrabObject undefineProperty(String name)
    {
        GrabValue gv = _values.get(name);
        if (gv == null) return this;
        if (gv.getChanged()) {
            decChanged();
        }
        if (gv.getHasValue()) {
            decHasValue();
        }
        gv._parent = null;
        _values.remove(name);
        return this;
    }

    public GrabValue at(String name)
    {
        GrabValue gv = _values.get(name);
        if (gv == null) throw new Error("Can't find property: " + name);
        return gv;
    }

    public GrabObject setValue(String name, boolean v)
    {
        GrabValue gv  = _values.get(name);
        if (gv == null) {
            throw new Error("Boolean property " + name + " does not exists");
        }
        GrabBoolean gvb = (GrabBoolean)gv;
        gvb.setValue(v);
        return this;
    }
    public GrabObject setValue(String name, double v)
    {
        GrabValue gv  = _values.get(name);
        if (gv == null) {
            throw new Error("Number property " + name + " does not exists");
        }
        GrabNumber gvb = (GrabNumber)gv;
        gvb.setValue(v);
        return this;
    }

    public GrabObject setValue(String name, String v)
    {
        GrabValue gv  = _values.get(name);
        if (gv == null) {
            throw new Error("String property " + name + " does not exists");
        }
        GrabString gvb = (GrabString)gv;
        gvb.setValue(v);
        return this;
    }

    public final Map<String, GrabValue> getValues() {
        return _values;
    }
    @Override
    public void resetChanged()
    {
        for(Map.Entry<String, GrabValue> i:_values.entrySet()) {
            i.getValue().resetChanged();
        }
    }
    @Override
    public void resetValue()
    {
        for(Map.Entry<String, GrabValue> i:_values.entrySet()) {
            i.getValue().resetValue();
        }
    }
}
